﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;


[System.Runtime.CompilerServices.CompilerGenerated]
public partial class StoredProcedures
{
    [System.Runtime.CompilerServices.CompilerGenerated]
    private static string _password = null;

    [Microsoft.SqlServer.Server.SqlProcedure]
    [System.Runtime.CompilerServices.CompilerGenerated]
    public static void spSetPassword(SqlString password)
    {
        string foo = password.ToString();
        System.Threading.Interlocked.Exchange(ref _password, foo);
    }

    [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
    public static SqlBinary Encrypt(SqlString input)
    {
        SqlConnection conn = new SqlConnection(@"context connection=true");
        conn.Open();

        SqlCommand cmm = conn.CreateCommand();
        cmm.CommandText = "select EncryptByCert(Cert_ID('OSMCertificate'), @cleartext)";
        cmm.Parameters.Add(new SqlParameter("@cleartext", input));
        SqlDataReader rdr = cmm.ExecuteReader();
        rdr.Read();

        return rdr.GetSqlBinary(0);
    }

    [Microsoft.SqlServer.Server.SqlFunction(DataAccess=DataAccessKind.Read)]
    public static SqlString Decrypt(SqlBinary input)
    {
        if (_password == null)
            throw new Exception("Missing password");

        SqlConnection conn = new SqlConnection(@"context connection=true");
        conn.Open();

        SqlCommand cmm = conn.CreateCommand();
        cmm.CommandText = "select DecryptByCert(Cert_ID('OSMCertificate'), @encryptedtext, @password)";
        cmm.Parameters.Add(new SqlParameter("@encryptedtext", input));
        cmm.Parameters.Add(new SqlParameter("@password", _password));
        SqlDataReader rdr = cmm.ExecuteReader();
        rdr.Read();

        if (rdr.IsDBNull(0))
            return SqlString.Null;
        else
        {
            SqlBinary b = rdr.GetSqlBinary(0);

            return new SqlString(System.Text.Encoding.Unicode.GetString(b.Value));
        }
    }
};
